package com.terren.excavator.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.alibaba.fastjson.JSON;
import com.terren.excavator.entity.GridColumn;

/**
 * 常用工具类
 * @author Administrator
 *
 */
public class CommonUtil {
	private static Logger logger = getLogger(CommonUtil.class);
	
	/**
	 * 获得 logger
	 * @param clazz
	 * @return
	 */
	public static Logger getLogger(Class<?> clazz){
		Logger logger = Logger.getLogger(CommonUtil.class);
		return logger;
	}
	
	/**
	 * 往session 中存数据
	 * @param name
	 * @param obj
	 */
	public static void setSessionAttribute(String name,Object obj){
		HttpSession session = ServletActionContext.getRequest().getSession();
		
		session.setAttribute(name, obj);
	}
	
	/**
	 * 从 session 中获得数据
	 */
	public static Object getSessionAttribute(String name){
		HttpSession session = ServletActionContext.getRequest().getSession();
		Object object = session.getAttribute(name);
		return object;
	}
	
	/**
	 * 输出 Ajax 返回的内容
	 */
	public static void printResult(String result){
		logger.debug("pringResult=>" + result);
		//获得response
		HttpServletResponse response = ServletActionContext.getResponse();
		//设置输出UTF-8编码
		response.setContentType("text/html;charset=utf-8");
		
		//获得输出流
		PrintWriter out = null;
		
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(out != null){
				//将数据写入输出流
				out.print(result);
				//清楚数据流缓冲区
				out.flush();
				//关闭输出流
				out.close();
			}
		}
	}
	
	/**
	 * 拼接 column 字符串
	 * @param fieldSet
	 * @return
	 */
	public static String getColumnJson(Set<String> fieldSet){
		/*
		"columns":[[{"field":"ROLE_ID","title":"ROLE_ID","width":100,"resizable":true},  
        {"field":"NAME","title":"NAME","width":100,"resizable":true},  
        {"field":"CREATE_DATE","title":"CREATE_DATE","width":100,"resizable":true},  
        {"field":"DESCRIPTION","title":"DESCRIPTION","width":100,"resizable":true}]],
		*/
		
		List<GridColumn> columnList = new ArrayList<GridColumn>();
		
		for(String fieldName : fieldSet){
			
			if(!"url".equalsIgnoreCase(fieldName)){
				GridColumn grid = new GridColumn(fieldName);
				
				columnList.add(grid);
			}
		}
		String jsonResult = JSON.toJSONString(columnList);
		return jsonResult;
	}
	
	/**
	 * 返回ajax执行结果
	 * @param isSuccess
	 * @param msg
	 * @return
	 */
	public static String returnAjaxJson(boolean isSuccess,String msg){
		String json = "";
		if(isSuccess){
			json = "{\"success\":\"" + msg + "\"}";
		}else{
			json += "{\"error\":\"" + msg + "\"}";
		}
		return json;
	}
	
	/**
	 * 去掉首尾所有空格
	 * @param text
	 * @return
	 */
	public static String trimBlank(String text){
		String result = null;
		if(text != null){
			//分别是 全角空格     不知道什么空格     半角标准空格
			String regex = "(^[　  ]*)|([　  ]*$)";
			result = text.replaceAll(regex, "");
		}
		return result;
	}
	
	/**
	 * 获得web项目的主路径
	 * @return
	 */
	public static String getWebMainPath(){
		String mainPath = ServletActionContext.getServletContext().getRealPath("/");
		
		return mainPath;
	}
	
	/**
	 * 删除文件文件及空文件夹
	 * @param filePath
	 */
	public static boolean deleteFile(String filePath){
		File file = new File(filePath);
		boolean flag = false;
		if(file.exists()){
			flag = file.delete();
		}else{
			logger.info("file does not exists : " + filePath);
		}
		return flag;
	}
	
	/**
	 * 删除非空文件夹
	 * @param filePath
	 * @return
	 */
	public static void deleteFolder(File path){
		if (path.exists()){
			if (path.isFile()) {
				path.delete();
			}else{
				File[] files = path.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFolder(files[i]);
				}
				path.delete();
			}
		}
	}
	
	/**
	 * 创建路径所表示的文件夹
	 */
	public static void createFilePath(String path){
		File indexFolder = new File(path);
		
		//路径不存在则新建
		if(!indexFolder.exists()){
			indexFolder.mkdirs();
		}
	}
	
	/**
	 * 格式化提取到的 publishDay
	 * yyyyMMddHHmmss
	 * @param publishDay
	 * @return 
	 */
	public static String formatPublishDay(String publishDay){
		//2013年11月28日11:23:63
		if(publishDay != null){
			publishDay = publishDay.replaceAll("年", "");
			publishDay = publishDay.replaceAll("月", "");
			publishDay = publishDay.replaceAll("日", "");
			publishDay = publishDay.replaceAll("/", "");
			publishDay = publishDay.replaceAll("-", "");
			publishDay = publishDay.replaceAll(" ", "");
			publishDay = publishDay.replaceAll(":", "");
			//20131128112363
			//如果没有秒，自动补秒
			/*不对原始数据做干预
			if(publishDay.length()< 14){
				publishDay += "00";
			}
			*/
			
			//publishDay = publishDay.substring(0, 10) + " " + publishDay.substring(10);
		}
		return publishDay;
	}
	
	public static void main(String[] args) {
		Set<String> fieldSet = new HashSet<String>();
		
		fieldSet.add("url");
		fieldSet.add("title");
		fieldSet.add("contentid");
		
		String s2 = getColumnJson(fieldSet);
		
		System.out.println(s2);
	}
	
}
